package com.trkj.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.trkj.base.newwork.ProgressBarDataFromRemote;
import com.trkj.taoruiyun.R;

/**
 * 与数据有关的可刷新Fragment
 * Created by LiZanhong on 2015/06/21.
 */
public abstract class BaseDataRefreshFragment extends  BaseRefreshFragment
        implements ListView.OnItemClickListener{
    protected ListView listView;
    protected JSONArray data;
    protected View root;

    private BaseAdapter adapter;

    private int page = 1;
    private int rows = 15;

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public void setAdapter(BaseAdapter adapter) {
        this.adapter = adapter;
    }

    public BaseAdapter getAdapter() {
        return adapter;
    }

    public ListView getListView() {
        return listView;
    }


    public JSONArray getData() {
        if(data == null) data = new JSONArray();
        return data;
    }

    /**
     * 获取数据访问的url
     * @return
     */
    public abstract String getUrl();

    /**
     * 清除数据
     */
    public void clear(){
        if(getData() == null) return;
        getData().clear();
    }

    @Override
    public void onRefresh() {
        refreshData();
        super.onRefresh();//必须要调用，用于停止动画
    }

    @Override
    public void onLoad() {
        loadData();
        super.onLoad();//必须要调用，用于停止动画
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (root != null)
            return root;

        root = inflater.inflate(R.layout.fragment_share_listview, container, false);
        listView = (ListView) root.findViewById(R.id.list);
        listView.setAdapter(getAdapter());
        listView.setOnItemClickListener(this);

        setSwiftLayout(root, R.id.fsl_swipe_container);
        initData();

        return root;
    }

    /**
     * 初始化数据（第一页显示的时候）
     */
    protected void initData() {
        refreshData();
    }


    /**
     * 下拉刷新数据
     */
    public void refreshData() {
        int tmpPage = getPage();
        setPage(1);

        ProgressBarDataFromRemote dataFromRemote = new ProgressBarDataFromRemote(getActivity());
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                if (result != null) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    boolean success = jsonObject.getBoolean("success");

                    if (success) {
                        JSONArray array = jsonObject.getJSONArray("data");
                        JSONArray temp = new JSONArray(data);

                        DataFilter.removeAllSame(data, temp);//删除已经存在的元素
                        if (array.size() == 0) {
                            //toast("没有刷到最新数据哦");
                        } else {
                            //只添加最新的数据
                            DataFilter.applyChange(data, temp);//更新修饰后的数据
                            data.addAll(0, array);//追加到原来数据的前面

                            if(getAdapter() == null)
                                throw new IllegalArgumentException("没有为ListView指定Adapter");
                            ((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
                        }
                    } else {
                        toast("获取数据失败，请检查网络或升级到最新版");
                    }
                }
            }
        });

        dataFromRemote.execute(getUrl());
        setPage(tmpPage);
    }

    /**
     * 上拉加载数据
     */
    public void loadData() {
        this.page ++;

        ProgressBarDataFromRemote dataFromRemote = new ProgressBarDataFromRemote(getActivity());
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                if (result != null) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    boolean success = jsonObject.getBoolean("success");

                    if (success) {
                        JSONArray array = jsonObject.getJSONArray("data");
                        if (array != null && array.size() > 0) {
                            DataFilter.removeAllSame(data, array);//删除已经存在的元素
                            data.addAll(array);
                            if(getAdapter() == null)
                                throw new IllegalArgumentException("没有为ListView指定Adapter");
                            ((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
                        } else {
                            toast("没有更多数据");
                            page--;//没有数据，要把刚才+1的抵消掉
                        }
                    } else {
                        toast("获取数据失败，请检查网络或升级到最新版");
                    }
                }
            }
        });

        dataFromRemote.execute(getUrl());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}
